﻿/// <reference path="../libraries/q.js" />
var FileHandler = (function () {
    
    var writeDefered = Q.defer();

    var ReadTextFile = function (fileName) {
        //Create promise
        var readDefered = Q.defer();

        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotReadFS, fail); //potential problems with the file place

        function gotReadFS(fileSystem) {
            fileSystem.root.getFile(fileName, null, gotReadEntry, fail);
        }

        function gotReadEntry(fileEntry) {
            fileEntry.file(gotReadFile, fail);
        }

        function gotReadFile(file) {
            readAsText(file);
        }

        function readAsText(file) {
            var reader = new FileReader();
            reader.onloadend = function (evt) {
                //passing to the promise
                readDefered.resolve(evt.target.result);
            };
            reader.readAsText(file);
        }

        function fail(error) {
            console.log(error.code);
            //pass error to the promise
            readDefered.reject(error);
        }

        return readDefered.promise;
    }

    var WriteTextFile = function (fileName, fileContent) {

        var writeDefered = Q.defer();

        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotWriteFS, fail);
        
        function gotWriteFS(fileSystem) {
            fileSystem.root.getFile(fileName, { create: true, exclusive: false }, gotWriteEntry, fail);
        }

        function gotWriteEntry(fileEntry) {
            fileEntry.createWriter(gotFileWriter, fail);
        }

        function gotFileWriter(writer) {
            writer.onwriteend = function (evt) {
                //The writing of the file returns a true value for being successful.
                writeDefered.resolve(true);
            };

            //move the writer to the end of the file (should start from begining if file is empty)
            //writer.seek(writer.length);
            writer.write(fileContent);
        }

        function fail(error) {
            //if writing was unsuccessful, just propagate the error
            writeDefered.reject(error);
        }

        return writeDefered.promise;
    }

    return {
        readTextFile: ReadTextFile,
        writeTextFile: WriteTextFile
    }
}())